﻿/* ************************************************************************************* 
 * CREATED BY:          GIAPCM
 * CREATED DATE:        10/02/2009
 * PROJECT:             MC ENT WEBSITE PROJECT
 * PURPOSE:             
 * MODIFIED BY:         None
 * MODIFIED DATE:       None
 * MODIFIED REASON:     None
 * NOTES:               None
 **************************************************************************************/
using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Telerik.Web.UI;
using MCWEBSITE.BUL;
using MCWEBSITE.ENTITY;
using MCWF;

public partial class Modules_WebsiteBackEnd_wucProductsDetail : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string[] ResourceDirectory = { "" };
        ResourceDirectory[0] = lblResourceDirectoryTemp.Text.Trim();
    }

    #region "UTILITIES"

    #endregion

    #region "BINDING DATA CONTROLS"

    protected void rcbLanguage_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        this.BindProductType(rcbLanguage.SelectedValue);
        this.BindProductCategory(rcbLanguage.SelectedValue);
    }

    public void BindDataControl()
    {
        this.BindLanguage();
        this.BindProductType(rcbLanguage.SelectedValue);
        this.BindProductCategory(rcbLanguage.SelectedValue);
    }

    public void BindLanguage()
    {
        List<websiteLanguageInfo> objLanguage = websiteLanguageBUL.GetAll();
        rcbLanguage.DataSource = objLanguage;
        rcbLanguage.DataValueField = "LanguageCode";
        rcbLanguage.DataTextField = "languageName";
        rcbProductType.ClearSelection();
        rcbLanguage.DataBind();
        //rcbLanguage.SelectedIndex = rcbLanguage.FindItemIndexByValue("en-EN");
    }

    public void BindProductType(string strLanguage)
    {
        List<websiteProductTypeInfo> objCat = websiteProductTypeBUL.Search(strLanguage);
        rcbProductType.DataSource = objCat;
        rcbProductType.DataValueField = "ProductTypeID";
        rcbProductType.DataTextField = "TypeName";
        rcbProductType.ClearSelection();
        rcbProductType.DataBind();
    }

    public void BindProductCategory(string strLanguage)
    {
        List<websiteProductCategoryInfo> objCat = websiteProductCategoryBUL.Search(strLanguage);
        rcbProductCategory.DataSource = objCat;
        rcbProductCategory.DataValueField = "CategoryID";
        rcbProductCategory.DataTextField = "CategoryName";
        rcbProductCategory.ClearSelection();
        rcbProductCategory.DataBind();
    }

    protected void BindDataDetail(int ItemID)
    {
        string[] ResourceDirectory = { "" };
        if (ItemID != -1)
        {
            // Bind Resources
            websiteProductInfo objNews = websiteProductBUL.Load(ItemID);
            lbProductID.Text = Convert.ToString(objNews.ItemID);
            tbProductName.Text = Convert.ToString(objNews.ItemName);            
            tbProductCode.Text = Convert.ToString(objNews.ItemCode);
            redtDescription.Content = Convert.ToString(objNews.Description);          
            tbPrice.Text = objNews.Atribute1;
            rcbLanguage.Items.FindItemByValue(Convert.ToString(objNews.LanguageCode)).Selected = true;
            BindProductType(rcbLanguage.SelectedValue);
            BindProductCategory(rcbLanguage.SelectedValue);
            rcbProductType.Items.FindItemByValue(Convert.ToString(objNews.TypeID)).Selected = true;
            rcbProductCategory.Items.FindItemByValue(Convert.ToString(objNews.CategoryID)).Selected = true;
            // Check Product directory
            ResourceDirectory[0] = objNews.Image;
            string ResourcePhysicalPath = Server.MapPath(ResourceDirectory[0]);
            DirectoryInfo ResourcePhysicalDir = new DirectoryInfo(ResourcePhysicalPath);
            if (!ResourcePhysicalDir.Exists)
            {
                ResourcePhysicalDir.Create();
            }
            lblResourceDirectoryTemp.Text = objNews.Image;
        }
        else
        {
            lbProductID.Text = "";
            tbProductName.Text = "";
            tbProductCode.Text = "";
            redtDescription.Content = "";
            tbPrice.Text = "";
            // Products directory
            ResourceDirectory[0] = "~/Resources/Products/temp";
            string TempDirectory = "";
            if (lblResourceDirectoryTemp.Text == "")
            {
                for (int i = 1; i <= 200; i++)
                {
                    TempDirectory = Server.MapPath(ResourceDirectory[0]);
                    TempDirectory = TempDirectory + "\\" + i.ToString() + "\\";
                    DirectoryInfo ResourcePhysicalDirectory = new DirectoryInfo(TempDirectory);
                    if (!ResourcePhysicalDirectory.Exists)
                    {
                        // Create Product directory
                        ResourcePhysicalDirectory.Create();
                        ResourceDirectory[0] = ResourceDirectory[0] + "\\" + ResourcePhysicalDirectory.Name;
                        lblResourceDirectoryTemp.Text = ResourceDirectory[0];
                        break;
                    }
                }
            }
            else
            {
                ResourceDirectory[0] = lblResourceDirectoryTemp.Text;
            }
        }
    }

    #endregion

    #region "DATA HANDLING PROCEDURE/FUNCTION"

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    protected int InsertRow(NewsToolbarButton ClickedButton)
    {
        websiteProductInfo objNews = new websiteProductInfo();
        objNews.ItemID = 0;
        objNews.LanguageCode = rcbLanguage.SelectedValue;
        objNews.ItemName = tbProductName.Text.Trim();        
        objNews.ItemCode = tbProductCode.Text.Trim();
        objNews.CategoryID = Convert.ToInt32(rcbProductCategory.SelectedValue);
        objNews.TypeID = Convert.ToInt32(rcbProductType.SelectedValue);
        objNews.Description = Convert.ToString(redtDescription.Content);
        objNews.Sale = Convert.ToInt32(tbPrice.Text);
        objNews.SaleDiscount = Convert.ToInt32(tbSalePrice.Text);
        
        // Build ActionCode      
        // Perform save action
        try
        {
            // Save news object
            int InsertedProductId = websiteProductBUL.Save(objNews);
            // Moving all Product from temp directory to newly created one
            string ResourceDirectory = "~/Resources/Products/" + InsertedProductId.ToString() + "/";
            // Insert NewsThumbImg object to NewsThumbImg table
            websiteProductBUL.InsertResource(InsertedProductId, ResourceDirectory);
            // Processing Product 
            // Create Product directory and thumb directory approximately
            DirectoryInfo ResourcesDir = new DirectoryInfo(Server.MapPath(ResourceDirectory));
            if (!ResourcesDir.Exists) ResourcesDir.Create();
            Utilities.CopyDirectory(Server.MapPath(lblResourceDirectoryTemp.Text), Server.MapPath(ResourceDirectory), true);
            // Delete temp directory
            DirectoryInfo TempDir = new DirectoryInfo(Server.MapPath(lblResourceDirectoryTemp.Text));
            TempDir.Delete(true);
            // Return result
            return 1;
        }
        catch
        {
            return -1;
        }
    }
   
    protected int DeleteRow()
    {
        websiteProductInfo objNews = websiteProductBUL.Load(Convert.ToInt32(lbProductID.Text));
        // Delete Product directory
        DirectoryInfo ResourceDirectory = new DirectoryInfo(Server.MapPath(objNews.Image));
        if (ResourceDirectory.Exists)
            ResourceDirectory.Delete(true);
        // Delete News object
        return websiteProductBUL.Remove(Convert.ToInt32(lbProductID.Text.Trim()));
    }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    protected int UpdateRow(NewsToolbarButton ClickedButton)
    {
        websiteProductInfo objNews = new websiteProductInfo();
        objNews.ItemID = Convert.ToInt32(lbProductID.Text);
        objNews.LanguageCode = rcbLanguage.SelectedValue;
        objNews.ItemName = tbProductName.Text.Trim();
        objNews.ItemCode = tbProductCode.Text.Trim();
        objNews.CategoryID = Convert.ToInt32(rcbProductCategory.SelectedValue);
        objNews.TypeID = Convert.ToInt32(rcbProductType.SelectedValue);
        objNews.Description = Convert.ToString(redtDescription.Content);
        objNews.Sale = Convert.ToInt32(tbPrice.Text);
        objNews.SaleDiscount = Convert.ToInt32(tbSalePrice.Text);

        // Perform save action
        try
        {
            // Save news object
            if (ClickedButton == NewsToolbarButton.SAVEBUTTON)
            {
                objNews.IsActive = websiteProductBUL.Load(Convert.ToInt32(lbProductID.Text)).IsActive;
                return websiteProductBUL.Save(objNews);
            }
            else
            {
                objNews.IsActive = true;
                return websiteProductBUL.Save(objNews);
            }
        }
        catch
        {
            return -1;
        }
    }

    #endregion

    #region "PUBLIC PROCEDURE/FUNCTION"
    /// <summary>
    /// 
    /// </summary>
    /// <param name="ClickedButton"></param>
    /// <returns></returns>   
    public string PerformToolbarEvent(NewsToolbarButton ClickedButton)
    {
        string ResultString = "";
        int ReturnResult;

        // Create a new news and save OR create a new news and submit
        if (lblCurrentMode.Text.ToString().ToUpper() == NewsToolbarStatus.NEW.ToString().ToUpper() &&
            (ClickedButton == NewsToolbarButton.SAVEBUTTON || ClickedButton == NewsToolbarButton.SUBMITBUTTON))
        {
            if (Page.IsValid)
            {
                ReturnResult = this.InsertRow(ClickedButton);
                lblResourceDirectoryTemp.Text = "";
                if ((int)ReturnResult > 0) ResultString = "Bản ghi được bổ xung thành công";
                else ResultString = "Lỗi trong quá trình bổ xung bản ghi";
            }
        }

        // Edit a news and save OR Edit a news and submit
        if (lblCurrentMode.Text.ToString().ToUpper() == NewsToolbarStatus.EDIT.ToString().ToUpper() &&
            (ClickedButton == NewsToolbarButton.SAVEBUTTON || ClickedButton == NewsToolbarButton.SUBMITBUTTON))
        {
            if (Page.IsValid)
            {
                ReturnResult = this.UpdateRow(ClickedButton);
                lblResourceDirectoryTemp.Text = "";
                if ((int)ReturnResult > 0) ResultString = "Bản ghi được cập nhật thành công";
                else ResultString = "Lỗi trong quá trình cập nhật bản ghi";
            }
        }

        // Edit a news and delete
        if (lblCurrentMode.Text.ToString().ToUpper() == NewsToolbarStatus.EDIT.ToString().ToUpper() &&
            ClickedButton == NewsToolbarButton.DELBUTTON)
        {
            ReturnResult = this.DeleteRow();
            lblResourceDirectoryTemp.Text = "";
            if ((int)ReturnResult > 0) ResultString = "Bản ghi được xóa thành công";
            else ResultString = "Lỗi trong quá trình xóa bản ghi";
        }
        //Modify by Huyenmt
        //Upload News Image
        if (ClickedButton == NewsToolbarButton.IMAGEBUTTON)
        {
            // Show upload images windows
            ProductUploadWindow.NavigateUrl = "~/Default.aspx?Page=ResourceUpload&ResourceDir=" + lblResourceDirectoryTemp.Text;
            ProductUploadWindow.VisibleOnPageLoad = true;
        }
        // Undo
        if (lblCurrentMode.Text.ToString().ToUpper() == NewsToolbarStatus.EDIT.ToString().ToUpper() &&
            ClickedButton == NewsToolbarButton.UNDOBUTTON)
        {
            ResultString = "LỰA CHỌN TÁC VỤ TRÊN THANH CÔNG CỤ";
            if (lblCurrentMode.Text.ToString().ToUpper() == NewsToolbarStatus.NEW.ToString().ToUpper())
            {
                DirectoryInfo ResourceDirectoryInfo = new DirectoryInfo(Server.MapPath(lblResourceDirectoryTemp.Text));
                if (ResourceDirectoryInfo.Exists)
                    ResourceDirectoryInfo.Delete(true);
            }
        }
        return ResultString;
    }


    public void SetControlMode(NewsToolbarStatus ToolbarMode)
    {
        if (ToolbarMode == NewsToolbarStatus.NEW)
        {
            lblDetailMode.Text = "TẠO MỚI BẢN GHI";
            lblCurrentMode.Text = NewsToolbarStatus.NEW.ToString().ToUpper();
        }
        if (ToolbarMode == NewsToolbarStatus.EDIT)
        {
            lblDetailMode.Text = "CHỈNH SỬA BẢN GHI";
            lblCurrentMode.Text = NewsToolbarStatus.EDIT.ToString().ToUpper();
        }
    }

    public void SetDetailData(int ItemID)
    {
        this.BindDataControl();
        this.BindDataDetail(ItemID);
    }

    public void RefreshDetailView()
    {
        if (lblCurrentMode.Text.ToString().ToUpper() == NewsToolbarStatus.NEW.ToString().ToUpper())
        {
            this.BindDataDetail(-1);
        }
        else
        {
            int SelectedItemID = Convert.ToInt32(lbProductID.Text.Trim());
            this.BindDataDetail(SelectedItemID);
        }
    }

    #endregion
}
